//
//  WDLoginController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDLoginController.h"
#import "WDForgetController.h"
#import "WDNavController.h"
#import "WDLoginMessage.h"
#import "ControllerTool.h"
#import "WDPromptBox.h"
#import "LeftMenViewController.h"
#import "WDLinkMessage.h"
#import "SecurityUtil.h"
#import "WDBusiness.h"
#import "WDProduct.h"
#import "WDCarList.h"
#import "WDStseries.h"

@interface WDLoginController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *userText;
@property (weak, nonatomic) IBOutlet UITextField *pwdText;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
/** 登录信息 */
@property (nonatomic, strong) WDLoginMessage *loginMessage;

@end

@implementation WDLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //监听文本框的实时输入
    [self.userText addTarget:self action:@selector(userValueChange) forControlEvents:UIControlEventEditingChanged];
    
    [self.pwdText addTarget:self action:@selector(pwdValueChange) forControlEvents:UIControlEventEditingChanged];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self checkNewWorking];
    
    //隐藏导航条
    self.navigationController.navigationBar.hidden = YES;
    
    //取得保存的用户名
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    if (userName) {
        self.userText.text = userName;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 监听textField的输入
- (void)userValueChange {
    
    if (self.pwdText.text.length >= 6 && self.userText.text.length > 0) {
        
        self.loginBtn.enabled = YES;
        
    } else {
        
        self.loginBtn.enabled = NO;
        
    }
    
}

- (void)pwdValueChange {
    
    if (self.pwdText.text.length >= 6 && self.userText.text.length > 0) {
        
        self.loginBtn.enabled = YES;
        
    } else {
        
        self.loginBtn.enabled = NO;
        
    }
    
}

#pragma mark - 点击事件
//登录
- (IBAction)clickLoginBtn
{
    
    [self.view endEditing:YES];
    
    self.loginBtn.enabled = NO;
    
    //拼接请求体
    NSString *password = [MD5Util md5:self.pwdText.text];
    
    NSDictionary *parameters = @{
                                 @"account":self.userText.text,
                                 @"password":password,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin];
    //发请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = 5.0;
    
    [SVProgressHUD show];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //判断车型车系是否归档成功
        //解档车品牌信息
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSString *archiverPath = [path stringByAppendingPathComponent:WDCarListFile];
        
        NSArray *carArr = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
        
        if (!carArr.count) {//重新归档
            [self getCarType];
        }
        
        [SVProgressHUD dismiss];
        //保存cookie
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: [NSURL URLWithString:url]];
        
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            if ([cookie.name isEqualToString:@"logininfo"]){
                
                //AES解密cookie
                
                //1.URLDecode
                NSString *urlDecode = [self URLDecodedString:cookie.value];
                
                //2.base64Decode
                NSData *data = [[NSData alloc] initWithBase64EncodedString:urlDecode options:0];
                
                //3.AES解密
                NSString *decodeData = [SecurityUtil decryptAESData:data];
                
                NSArray *ruleCode = [decodeData componentsSeparatedByString:@","];
                //解密字符串 -> 数组存进偏好设置里
                [[NSUserDefaults standardUserDefaults] setObject:ruleCode forKey:verStr];
            }
        }
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
        
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:url];
        
        self.loginMessage = [WDLoginMessage mj_objectWithKeyValues:responseObject];
        
        if ([self.loginMessage.error_code isEqualToString:@"0"]) {//登录成功
            
            //保存用户名
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            
            [userDefault setObject:self.userText.text forKey:@"userName"];
            
            [userDefault setInteger:self.loginMessage.uid forKey:@"uid"];
            
            [userDefault setObject:responseObject[@"work_city"] forKey:@"workCity"];
            
            [userDefault setBool:YES forKey:@"loginAgain"];
            
            [userDefault setObject:responseObject[@"image_url"] forKey:@"userIcon"];
            
            [userDefault setObject:self.loginMessage.name forKey:@"personName"];
            
            [userDefault setObject:self.loginMessage.phone forKey:@"personPhone"];
            
            [userDefault setObject:self.loginMessage.position_desc forKey:@"positioDesc"];
            
            [self setChannel];//更新cid
            
            [self getAddressList];//获取员工通讯录
            
            [self getBusinessList];//获取商户列表
            
            [self getFinanceList];//获取金融产品列表
            
            [WDPromptBox showPromptBoxWithMassage:@"登录成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [[UIApplication sharedApplication].delegate window].rootViewController = [[ControllerTool shareOpenController] getDrawerController];
                
                LeftMenViewController *leftVC = (LeftMenViewController *)[[ControllerTool shareOpenController] getDrawerController].leftDrawerViewController;
                
                leftVC.defaultIndex = 1;
                
            });
            
        } else {
            
            self.loginBtn.enabled = YES;
            
            [WDPromptBox showPromptBoxWithMassage:self.loginMessage.error_msg];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        
        self.loginBtn.enabled = YES;
        
        //WDLog(@"%@", error);
        
        [WDPromptBox showPromptBoxWithMassage:error.userInfo[@"NSLocalizedDescription"]];
        
        //WDLog(@"%@", error);
    }];
}

#pragma mark - 请求接口
//更新channelID
- (void)setChannel
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *parameters = @{
                                 @"uid" : @(self.loginMessage.uid),
                                 @"channel_id" : [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"],
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLChannelID];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        
    }];
}

/** 员工通讯录 */
- (void)getAddressList
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:WDTimeStampLogin];
    
    time_stamp = (time_stamp == nil ? @"" : time_stamp);
    
    NSDictionary *parameters = @{
                                 @"time_stamp":time_stamp,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLAddress];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        //保存时间戳
        [userDefault setObject:responseObject[@"time_stamp"] forKey:WDTimeStampLogin];
        
        NSMutableArray *linkMessages = [WDLinkMessage mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        //归档
        NSString *path = [WDCachePath stringByAppendingPathComponent:WDAddressFile];
        
        //WDLog(@"%@", path);
        
        if ([NSKeyedArchiver archiveRootObject:linkMessages toFile:path]) {
            //WDLog(@"通讯录信息归档成功");
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        
    }];
    
}

/** 商户列表 */
- (void)getBusinessList
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"business_time_stamp"];
    
    time_stamp = (time_stamp == nil ? @"" : time_stamp);
    
    NSDictionary *parameters = @{
                                 @"time_stamp":time_stamp,
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListSupplier];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //商户列表保存进数据库
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        //保存时间戳
        [userDefault setObject:responseObject[@"time_stamp"] forKey:@"business_time_stamp"];
        
        NSArray *tempArr = [WDBusiness mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        
        if (tempArr.count) {
            
            //保存数据库
            [manager creatTable:NSStringFromClass([WDBusiness class]) WithPrimaryKey:@[@"id"]];
            
            [manager insertWithTable:NSStringFromClass([WDBusiness class]) andModelArr:tempArr];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
    }];
    
}

/** 金融产品列表 */
- (void)getFinanceList
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"time_stampF"];
    
    time_stamp = (time_stamp == nil ? @" " : time_stamp);
    
    NSDictionary *parameters = @{
                                 @"time_stamp":time_stamp,
                                 @"city_id":[[NSUserDefaults standardUserDefaults] objectForKey:@"workCity"],
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLProductList];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //金融产品列表保存进数据库
        NSMutableArray *models = [NSMutableArray array];
        
        models = [WDProduct mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        [userDefault setObject:responseObject[@"time_stamp"] forKey:@"time_stampF"];
        
        //保存到数据库中
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        
        [manager creatTable:NSStringFromClass([WDProduct class]) WithPrimaryKey:@[@"id"]];
        [manager insertWithTable:NSStringFromClass([WDProduct class]) andModelArr:models];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
    }];
}

- (void)getCarType
{
    NSDictionary *bodyDic = @{
                              @"time_stamp":@" ",
                              @"ctype":@3
                              };
    
    //车型
    [WDHTTPMethod getDataByString:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListBrand] BODYDic:bodyDic WithDataBlock:^(id data) {
        
        NSMutableArray *carLists = [WDCarList mj_objectArrayWithKeyValuesArray:data[@"data"]];
        
        //归档
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSString *archiverPath = [path stringByAppendingPathComponent:WDCarListFile];
        
        if ([NSKeyedArchiver archiveRootObject:carLists toFile:archiverPath]) {
            //            WDLog(@"车品牌信息归档成功");
        }
        
    }];
    
    //车系
    [WDHTTPMethod getDataByString:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListSeries] BODYDic:bodyDic WithDataBlock:^(id data) {
        
        NSMutableArray *seriesLists = [WDStseries mj_objectArrayWithKeyValuesArray:data[@"data"]];
        
        //归档
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSString *archiverPath = [path stringByAppendingPathComponent:WDCarSeriesFile];
        
        //        WDLog(@"%@", archiverPath);
        
        if ([NSKeyedArchiver archiveRootObject:seriesLists toFile:archiverPath]) {
            //            WDLog(@"车系信息归档成功");
        }
        
    }];
}


#pragma mark - url编解码
-(NSString *)URLEncodedString:(NSString *)str
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)str,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    
    return encodedString;
}

-(NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}


#pragma mark - 忘记密码
- (IBAction)clickForgetBtn
{
    
    WDForgetController *tempVC = [[WDForgetController alloc] init];
    
    tempVC.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempVC animated:YES];
}

#pragma mark - textFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.userText) {//用户名
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 30) {
            
            return NO;
        }
    } else if (textField == self.pwdText) {//密码
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        
        if (existedLength - selectedLength + replaceLength > 16) {
            
            return NO;
        }
        
    }
    
    return YES;
    
}

- (void)checkNewWorking
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                [WDPromptBox showPromptBoxWithMassage:@"未识别的网络"];
                
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                [WDPromptBox showPromptBoxWithMassage:@"网络连接中断"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
                break;
            default:
                break;
        }
        
    }];
    
    //开始监听
    [manager startMonitoring];
    
}

@end
